package annotationService.util;

import java.util.List;

public class PersistenceUtil{
	
	String fileName=null;
	String keyFieldName=null;
	String dbWorkspace=null;
	String fileFullPath=null;
	@SuppressWarnings("unchecked")
	Class clazz=null;
	
	@SuppressWarnings("unchecked")
	public PersistenceUtil(
			String fileName, 
			Class clazz,
			String keyFieldName,
			String dbWorkspace) {
		this.fileName = fileName;
		this.keyFieldName = keyFieldName;
		this.dbWorkspace = dbWorkspace;
		this.clazz=clazz;
		fileFullPath=dbWorkspace+fileName;
	}
	
	public Object load(Object obj) {
		return DB4OSimpler.generalOperate(
				fileFullPath,DB4OSimpler.OPERATION_LOAD,obj,keyFieldName
			);
	}
	public Object save(Object obj) {
		return DB4OSimpler.generalOperate(
				fileFullPath,DB4OSimpler.OPERATION_SAVE,obj,keyFieldName
			);
	}

	public Object update(Object obj) {
		return DB4OSimpler.generalOperate(
				fileFullPath,DB4OSimpler.OPERATION_UPDATE,obj,keyFieldName
			);
	}
	
	public boolean delete(Object obj) {
		return (Boolean)DB4OSimpler.generalOperate(
				fileFullPath,DB4OSimpler.OPERATION_DELETE,obj,keyFieldName
			);
	}

	@SuppressWarnings("unchecked")
	public List query(final Object obj) {
		return (List)DB4OSimpler.generalOperate(
				fileFullPath,DB4OSimpler.OPERATION_QUERY,obj,keyFieldName
			);
	}

	@SuppressWarnings("unchecked")
	public List list() {
		List list;
		try {
			list = (List)DB4OSimpler.generalOperate(
					fileFullPath,DB4OSimpler.OPERATION_LIST,clazz.newInstance(),keyFieldName
				);
			if (list!=null){
				list.add(new Pager());
			}
			return list;
		} catch (InstantiationException e) {
			e.printStackTrace();
			return null;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public boolean clear() {
		try {
			return (Boolean)DB4OSimpler.generalOperate(
					fileFullPath,DB4OSimpler.OPERATION_CLEAR,clazz.newInstance(),keyFieldName
				);
		} catch (InstantiationException e) {
			e.printStackTrace();
			return false;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return false;
		}
	}
	
}

